"""
用户购买管理路由
提供用户购买记录的添加和查询功能
"""

from typing import Optional
from fastapi import APIRouter, Header, Query, Body
from fastapi.responses import JSONResponse
from utils.password_utils import get_user_id_from_jwt
from db.operations import UserPurchasesOperations, BookOperations
from model.message_model import Message
from model.user_purchases_model import (
    UserPurchase,
    PurchaseRequest,
    PurchaseResponse,
)

# 创建用户购买相关的子路由
router = APIRouter(
    prefix="/purchases",
    tags=["purchases"],
    responses={404: {"description": "Not found"}},
)


@router.get("/", summary="用户购买管理接口信息")
async def get_purchases_info():
    """获取用户购买管理接口信息和使用示例"""
    api_info = {
        "message": "用户购买管理API接口",
        "endpoints": {
            "GET /api/purchases/": "获取用户购买管理接口信息",
            "POST /api/purchases/buy": "进行购买",
            "GET /api/purchases/get": "查询指定图书购买记录",
        },
        "examples": {
            "进行购买": {
                "url": "/api/purchases/buy",
                "method": "POST",
                "header": "Bearer token",
                "body": {"book_id": 123, "price": 29.8},
                "description": "购买图书ID为123的图书，支付29.8元",
            },
            "查询购买记录": {
                "url": "/api/purchases/get?book_id=123",
                "method": "GET",
                "header": "Bearer token",
                "description": "查询用户是否购买了图书ID为123的图书",
            },
        },
    }
    return JSONResponse(status_code=200, content=api_info)


@router.post("/buy", summary="进行购买")
async def purchase_book(
    request: PurchaseRequest = Body(..., description="购买信息"),
    authorization: Optional[str] = Header(None, description="Bearer token"),
):
    """用户购买图书"""
    # 去除Bearer前缀
    authorization = authorization.replace("Bearer ", "", 1) if authorization else None

    user_id = await get_user_id_from_jwt(authorization)
    if not user_id:
        return JSONResponse(
            status_code=401,
            content=Message(
                message="未授权或无效的token",
            ).model_dump(),
        )

    try:
        purchase_data = UserPurchase(
            user_id=user_id,
            book_id=request.book_id,
            price=request.price,
        ).model_dump()

        # 准备购买数据
        purchases_ops = UserPurchasesOperations()

        # 首先查询是否已经购买过该图书
        existing_purchase = await purchases_ops.batch_query_purchases(
            [{"user_id": user_id, "book_id": request.book_id}]
        )
        if existing_purchase:
            return JSONResponse(
                status_code=400,
                content=Message(
                    message="购买失败，您已经购买过该图书",
                ).model_dump(),
            )

        # 判断价格是否与图书价格一致
        book_ops = BookOperations()
        book_details = await book_ops.batch_query_books_by_ids([request.book_id])
        if not book_details:
            return JSONResponse(
                status_code=400,
                content=Message(
                    message="购买失败，图书不存在",
                ).model_dump(),
            )
        book_price = book_details[0].get("price")
        if book_price is None or book_price != request.price:
            return JSONResponse(
                status_code=400,
                content=Message(
                    message="购买失败，价格不正确",
                ).model_dump(),
            )

        result = await purchases_ops.batch_insert_purchases([purchase_data])

        if result == 0:
            return JSONResponse(
                status_code=400,
                content=Message(
                    message="购买失败，可能已经购买过该图书",
                ).model_dump(),
            )

        return JSONResponse(
            status_code=200,
            content=Message(
                message="购买成功",
            ).model_dump(),
        )

    except Exception as e:
        return JSONResponse(
            status_code=500,
            content=Message(
                message=f"购买失败: {str(e)}",
            ).model_dump(),
        )


@router.get("/get", summary="查询购买记录")
async def get_purchase_record(
    book_id: int = Query(..., description="图书ID"),
    authorization: Optional[str] = Header(None, description="Bearer token"),
):
    """查询用户是否购买了指定图书"""
    # 去除Bearer前缀
    authorization = authorization.replace("Bearer ", "", 1) if authorization else None

    user_id = await get_user_id_from_jwt(authorization)
    if not user_id:
        return JSONResponse(
            status_code=401,
            content=Message(
                message="未授权或无效的token",
            ).model_dump(),
        )

    try:
        purchases_ops = UserPurchasesOperations()

        user_book_id = {"user_id": user_id, "book_id": book_id}

        # 查询特定的用户-图书购买记录
        purchases_list = await purchases_ops.batch_query_purchases([user_book_id])

        if not purchases_list:
            return JSONResponse(
                status_code=400,
                content=PurchaseResponse(
                    message="未找到购买记录",
                    purchase_data=None,
                ).model_dump(),
            )

        # 返回单个购买记录
        purchase_data = purchases_list[0]
        return JSONResponse(
            status_code=200,
            content=PurchaseResponse(
                message="查询购买记录成功",
                purchase_data=UserPurchase(**purchase_data),
            ).model_dump(),
        )

    except Exception as e:
        return JSONResponse(
            status_code=500,
            content=Message(
                message=f"查询购买记录失败: {str(e)}",
            ).model_dump(),
        )
